<template>
  <el-dialog title="跟进信息" :close-on-click-modal="false" :visible.sync="visible" class="cu-dialog cu-dialog_center"
    lock-scroll width="800px">
    <el-form ref="elForm" :model="dataForm" size="small" label-width="100px" label-position="right"
      :disabled="!!isDetail" :rules="rules">
      <el-col :span="12">
        <el-form-item label="跟进时间" prop="time">
          <el-date-picker v-model="dataForm.time" placeholder="请选择" clearable required :style='{"width":"100%"}'
            type='datetime' format="yyyy-MM-dd HH:mm:ss" value-format="timestamp">
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="跟进内容" prop="content">
          <el-input v-model="dataForm.content" placeholder="请输入" required show-word-limit :style='{"width":"100%"}'
            type='textarea' :autosize='{"minRows":4,"maxRows":4}'>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="状态" prop="status">
          <el-input v-model="dataForm.status" placeholder="请输入" required show-word-limit :style='{"width":"100%"}'
            type='textarea' :autosize='{"minRows":4,"maxRows":4}'>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="聊天截图" prop="chatScreen">
          <custom-upload-img v-model="dataForm.chatScreen" :fileSize="5" sizeUnit="MB" :limit="9" type="track">
          </custom-upload-img>
        </el-form-item>
      </el-col>
    </el-form>
    <el-timeline class="timeline">
      <el-timeline-item v-for="(item, index) in tracks" :key="index" type="primary">
        <div class="el-timeline-content">
          <p class="text">
            时间：{{custom.dateFormat(item.time)}}</p>
          <p class="text">
            【{{ item.type | dynamicTreeCodeText(typeOptions)}}】
            <span v-if="item.channel">【{{ item.channel | dynamicTreeCodeText(channelOptions)}}】</span>
            {{item.content}}
          </p>

          <template v-if="item.chatScreen!=null">
            <transition-group class="el-upload-list el-upload-list--picture-card" tag="ul" name="el-list">
              <li class="el-upload-list__item is-success" v-for="(file,index) in JSON.parse(item.chatScreen)"
                :key="file.fileId">
                <el-image :src="file.url" :preview-src-list="getImgList(JSON.parse(item.chatScreen))"
                  class="el-upload-list__item-thumbnail" :z-index="10000" :ref="'image'+index">
                </el-image>
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(index)">
                    <i class="el-icon-zoom-in"></i>
                  </span>
                </span>
              </li>
            </transition-group>
          </template>
          <p class="time">
            <span>{{item.createUserName}} 提交于 {{custom.dateFormat(item.createTime)}}</span>
            <span class="del" @click="handleDel(item.id,index)">
              <i class="el-icon-delete"></i>删除
            </span>
          </p>
        </div>
      </el-timeline-item>
    </el-timeline>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{$t('common.cancelButton')}}</el-button>
      <el-button type="primary" @click="dataFormSubmit()" v-if="!isDetail" :loading="loading">
        {{$t('common.confirmButton')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { getCustomerTrackList, createCustomerTrack, delCustomerTrack } from '@/api/crm/customerTrack'
export default {
  components: {},
  data () {
    return {
      loading: false,
      visible: false,
      isDetail: false,
      dataForm: {
        customerId: '',
        time: undefined,
        content: '',
        status: '',
        chatScreen: ''
      },
      tracks: [],
      rules: {
        time: [
          {
            required: true,
            message: '请选择跟进时间',
            trigger: 'change'
          },
        ],
        content: [
          {
            required: true,
            message: '请输入跟进内容',
            trigger: 'blur'
          },
        ],
        status: [
          {
            required: true,
            message: '请输入状态',
            trigger: 'blur'
          },
        ],
      },
      channelOptions: [],
      typeOptions: [],

    }
  },

  created () {
    this.getChannelOptions()
    this.getTypeOptions()
  },

  methods: {
    getChannelOptions () {
      this.$store.dispatch('base/getDictionaryData', { sort: 'ConsultChannels' }).then(res => {
        this.channelOptions = this.isDetail ? res : res.filter(o => o.enabledMark == 1)
      })
    },
    getTypeOptions () {
      this.$store.dispatch('base/getDictionaryData', { sort: 'TrackType' }).then(res => {
        this.typeOptions = this.isDetail ? res : res.filter(o => o.enabledMark == 1)
      })
    },

    init (id) {
      this.dataForm.customerId = id || 0;
      this.dataForm.time = +new Date()
      this.visible = true;
      this.$nextTick(() => {
        this.$refs['elForm'].resetFields();
        if (this.dataForm.customerId) {
          this.loading = true
          getCustomerTrackList(this.dataForm.customerId).then(res => {
            this.tracks = res.data
            this.loading = false
          }).catch(err => {
            this.loading = false
          })
        }
      })
    },
    dataFormSubmit () {
      this.$refs['elForm'].validate((valid, objects) => {
        if (valid) {
          this.loading = true
          createCustomerTrack(this.dataForm).then((res) => {
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 1000,
              onClose: () => {
                getCustomerTrackList(this.dataForm.customerId).then(res => {
                  this.tracks = res.data;
                  this.$refs['elForm'].resetFields();
                  this.loading = false
                  this.$emit('refresh', true)
                })
              }
            })
          }).catch(() => {
            this.loading = false
          })
        } else {
          // 如果校验不通过，定位到固定的位置,只操作第一个即可
          Object.keys(objects).forEach((v, index) => {
            if (index === 0) {
              if (this.$refs[v]) {
                this.$refs[v].$el.scrollIntoView({
                  block: "center",
                  behavior: "smooth"
                });
              }
            }
          });
        }
      })
    },
    handleDel (id, index) {
      this.$confirm(this.$t('common.delTip'), this.$t('common.tipTitle'), {
        type: 'warning'
      }).then(() => {
        delCustomerTrack(id).then(res => {
          this.tracks.splice(index, 1);
          this.$message({ type: 'success', message: res.msg });
          this.$refs['elForm'].resetFields();
          this.$emit('refresh')
        })
      }).catch(() => { });
    },
    handlePictureCardPreview (index) {
      // 通过程序化方式触发el-image的预览功能
      const imageRef = this.$refs['image' + index]
      if (imageRef && imageRef[0]) {
        // 模拟点击图片来触发预览
        const imageElement = imageRef[0].$el.querySelector('img')
        if (imageElement) {
          imageElement.click()
        }
      }
    },
    getImgList (list) {
      const newList = list.map(o => o.url)
      return newList
    }
  }
}
</script>

<style lang="scss" scoped>
.timeline {
  padding-top: 350px;
}
>>> .el-timeline-content {
  p {
    padding: 0;
    margin: 0;
  }
  .text {
    line-height: 25px;
    margin-bottom: 10px;
    color: #475059;
    font-size: 14px;
    font-weight: bold;
  }
  .time {
    font-size: 12px;
    display: flex;
    justify-content: space-between;
    opacity: 0.4;
    .del {
      display: none;
      color: rgb(255, 91, 91);
      cursor: pointer;
      i {
        margin-right: 5px;
      }
    }
  }
  &:hover {
    .del {
      display: block;
    }
  }
}
</style>